/**
 * Created by Administrator on 2017/4/20.
 */


var Poker = require('../Poker/Poker');
var NN = require('../Poker/NN');

var PokerPlayer = require('../Poker/player').PokerPlayer;

var Const = require('./const');
var SubCode = require('../subCode');
var Rule = require('./rules');

exports.XQNNPlayer = PokerPlayer.extend({
    _robDealer: -1,             // 抢庄状态，-1/0/1 未选择/不抢/抢庄
    _selectedCards: null,     // 选择的三张牌

    init: function (uid, msg) {
        this._super(uid, msg);

        this.winNums = 0;
        this.defeated = 0;
        this.hasNiu = 0;
        this.noneNiu = 0;

        this._baseScore = 0;
        this._selectedCards = null;
        this._selectedMulti = 0;        //选择的倍数
        this.showNiu = {};
        this._stat.roundPattern = Const.Pattern.NONE;
        this.isSelected = false;
    },

    reset: function () {
        this._selectedCards = null;
        this._selectedMulti = 0;        //选择的倍数
        this.isSelected = false;
    },
    getMulti: function () {
        return this._selectedMulti;
    },
    setMulti: function (value) {
        this._selectedMulti = value
    },

    setSelectedCards: function (cardsArr) {
        if (!cardsArr || cardsArr.length == 0) {
            this._selectedCards = [];
            return true;
        }

        if (cardsArr.length != 3) {
            return false;
        }

        var cards = Poker.buildFromArray(cardsArr);
        var allExist = true;
        var allPoint = 0;

        ExObject.eachKeyNum(cards, function (card, num) {
            if (!card) {
                allExist = false;
            }

            if (this._handCards.getCardNum(card) < num) {
                allExist = false;
            }

            allPoint += NN.getPoint(card) * num;
        }.bind(this));

        if (!allExist) {
            return false;
        }

        if (allPoint % NN.BASE != 0) {
            return false;
        }

        this._selectedCards = [];
        cardsArr.forEach(function (card) {
            this._selectedCards.push(card);
        }.bind(this));

        return true;
    },

    isSelectedCards: function () {
        return (this._selectedCards) ? true : false;
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getInfo: function () {
        var info = this._super();
        info.remainScore = this._stat.remainScore;
        return info;
    },

    getReconnectInfo: function (isSelf) {
        var info = this._super(isSelf);

        if (isSelf) {
            info.selectCards = this._selectedCards;
            info.handCards = this._handCards.getInitCards();
        }
        info.isSelected = this.isSelected;
        info.pattern = 0;
        if (this.isSelected) {
            info.pattern = this._calcNiu();
            info.handCards = this._handCards.getInitCards();
        }
        info.score = this._stat.score;
        info.multi = this.getMulti();
        info.selectNum = (this._selectedCards) ? this._selectedCards.length : -1;

        return info;
    },

    getSettlementInfo: function () {
        var info = this._super();
        info.handCards = this._handCards.getInitCards();
        info.selectCards = this._selectedCards;
        var room = this.getRoom();
        if (room.selected) {
            if (this.getRoundScore() > 0) {
                this.winNums += 1;
            } else {
                this.defeated += 1;
            }
            if (this._stat.roundPattern > 1) {
                this.hasNiu += 1;
            } else {
                this.noneNiu += 1;
            }
        }
        info.winNums = this.winNums;
        info.defeated = this.defeated;
        info.hasNiu = this.hasNiu;
        info.noneNiu = this.noneNiu;

        info.multi = this.getMulti();

        return info;
    },

    settlementPattern: function () {
        if (!this._selectedCards) {
            //自动选出最优三张牌
            var results = NN.calcNiuCards(this._handCards.getInitCards());
            this._selectedCards = (results.length > 0) ? results[0] : [];
        }

        this._calcNiu();
        if (!this.showNiu[this._stat.roundPattern]) {
            this.showNiu[this._stat.roundPattern] = 1;
        } else {
            this.showNiu[this._stat.roundPattern] += 1;
        }
    },

    settlement: function () {
        this._super();

        var room = this.getRoom();
        var player = this;
        var fanbei = room.fanbei;

        if (room.MS == "LLZZ" || room.MS == "NNSZ") {
            var dealerPlayer = this.getRoom().getDealerPlayer();
            if (!dealerPlayer) {
                return;
            }

            if (this.uid() == dealerPlayer.uid()) {
                return;
            }
            var dealerPlayerScore = Const.PatternMulti[dealerPlayer._stat.roundPattern];
            var playerScore = Const.PatternMulti[player._stat.roundPattern];

            var dealerPattern = dealerPlayer._stat.roundPattern;
            var playerPattern = player._stat.roundPattern;
            if (fanbei == 2) {
                if (dealerPattern == Const.Pattern.NN || dealerPattern == Const.Pattern.N9 || dealerPattern == Const.Pattern.N7) {
                    dealerPlayerScore += 1;
                }
                if (playerPattern == Const.Pattern.NN || playerPattern == Const.Pattern.N9 || playerPattern == Const.Pattern.N7) {
                    playerScore += 1;
                }
            }

            if (dealerPlayer._stat.roundPattern > player._stat.roundPattern) {
                var score = player.getMulti() * dealerPlayerScore * room.baseScore;
                dealerPlayer.addRoundScore(score);
                player.addRoundScore(-score);
            } else if (dealerPlayer._stat.roundPattern < player._stat.roundPattern) {
                var score = player.getMulti() * playerScore * room.baseScore;
                player.addRoundScore(score);
                dealerPlayer.addRoundScore(-score);
            } else {
                var dealerPlayCard = dealerPlayer._getMaxCard();
                var playerCard = player._getMaxCard();
                if (NN.cardLT(dealerPlayCard, playerCard)) {
                    var score = player.getMulti() * dealerPlayerScore * room.baseScore;
                    dealerPlayer.addRoundScore(score);
                    player.addRoundScore(-score);
                } else {
                    var score = player.getMulti() * playerScore * room.baseScore;
                    player.addRoundScore(score);
                    dealerPlayer.addRoundScore(-score);
                }
            }
        }
    },

    onStartNewRound: function () {
        this._super();
        this.reset();
        this._stat.roundPattern = Const.Pattern.NONE;
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    /******************************************************************
     * 私有功能函数
     ******************************************************************/
    _calcNiu: function () {
        var room = this.getRoom();
        var selectCards = this._selectedCards;

        var pattern = Const.Pattern.NONE;
        //炸弹牛
        var allCardsArr = this._handCards.getInitCards();
        var firstNum = 1;
        var first = Poker.getPoint(allCardsArr[0]);
        for (var i = 1; i < allCardsArr.length; i++) {
            if (Poker.getPoint(allCardsArr[i]) == first) {
                firstNum += 1;
            }
        }
        if (firstNum == 4) {
            if (room.specialCard["ZhaDanNiu"]) {
                pattern = Const.Pattern.ZDN;
            }
        }
        if (firstNum == 1) {
            var secondNum = 1;
            var second = Poker.getPoint(allCardsArr[1]);
            for (var i = 2; i < allCardsArr.length; i++) {
                if (Poker.getPoint(allCardsArr[i]) == second) {
                    secondNum += 1;
                }
            }

            if (secondNum == 4) {
                if (room.specialCard["ZhaDanNiu"]) {
                    pattern = Const.Pattern.ZDN;
                }
            }
        }


        //五小牛
        var flag = true;
        allCardsArr.forEach(function (card) {
            if (NN.getPoint(card) >= 5) {
                flag = false;
            }
        });
        if (flag) {
            if (allCardsArr.reduce(function (a, b) {
                    return NN.getPoint(a) + NN.getPoint(b);
                }, 0) > 10) {
                flag = false;
            }
        }
        if (flag) {
            if (room.specialCard["WuXiaoNiu"]) {
                pattern = Const.Pattern.WXN;

            }
        }
        if (pattern) {
            this._stat.roundPattern = pattern;
            return pattern;
        }

        //五花牛
        var otherPoints = 0;
        allCardsArr.forEach(function (card) {
            if (selectCards.indexOf(card) == -1) {
                otherPoints += NN.getPoint(card);
            }
        });

        var nPoint = otherPoints % NN.BASE;
        var pattern = Const.Pattern.NONE;

        if (nPoint == 0) {
            var tag = 0;
            selectCards.forEach(function (card) {
                tag += NN.getPoint(card);
            });
            if (tag != 0 && (tag % NN.BASE == 0)) {
                pattern = Const.Pattern.NN;
                var minPoint = Poker.Point.MAX;
                var maxPoint = Poker.Point.MIN;
                allCardsArr.forEach(function (card) {
                    var point = Poker.getPoint(card);
                    minPoint = Math.min(minPoint, point);
                    maxPoint = Math.max(maxPoint, point);
                });

                if (minPoint >= Poker.Point.J && maxPoint <= Poker.Point.K) {
                    pattern = Const.Pattern.WHN;
                }
                if (!room.specialCard["WuHuaNiu"]) {
                    pattern = Const.Pattern.NN;
                }
            }
        } else {
            var tag = 0;
            selectCards.forEach(function (card) {
                tag += NN.getPoint(card);
            });
            if (tag != 0 && (tag % NN.BASE == 0)) {
                pattern = Const.Pattern['N' + nPoint];
            }
        }

        this._stat.roundPattern = pattern;
        return pattern;
    },
    _cardArrayToObj: function (arrayCards) {
        var obj = {};
        arrayCards.forEach(function (v) {
            if (obj[v]) {
                obj[v] += 1;
            } else {
                obj[v] = 1;
            }
        });
        return obj;
    },
    _cardObjToArray: function (arrayObj) {
        var keys = Object.keys(arrayObj);
        var temp = [];
        keys.forEach(function (v) {
            if (arrayObj[v]) {
                temp.push(v);
            }
        });
        return temp;
    },

    _getMaxCard: function () {
        if (this._stat.roundPattern == Const.Pattern.ZDN) {

            var allCardsArr = this._handCards.getInitCards();
            var firstNum = 1;
            var card = 0;
            var first = Poker.getPoint(allCardsArr[0]);
            for (var i = 1; i < allCardsArr.length; i++) {
                if (Poker.getPoint(allCardsArr[i]) == first) {
                    firstNum += 1;
                    card = allCardsArr[i];
                }
            }
            if (firstNum == 4) {
                return card;
            }
            if (firstNum == 1) {
                var secondNum = 1;
                var second = Poker.getPoint(allCardsArr[1]);
                for (var i = 2; i < allCardsArr.length; i++) {
                    if (Poker.getPoint(allCardsArr[i]) == second) {
                        secondNum += 1;
                        card = allCardsArr[i];
                    }
                }
                if (secondNum == 4) {
                    return card;
                }
            }
        }
        var maxCard = 0;
        //var selectCards = this._selectedCards;
        var allCardsArr = this._handCards.getInitCards();

        allCardsArr.forEach(function (card) {

            if (!maxCard || NN.cardLT(card, maxCard)) {
                maxCard = card;
            }

        });

        return maxCard;
    },
    // getInitHandCardPreCards: function () {
    
    //     var preCards = [];
    //     if (this._prehandcards) {
    //         for (var i = 0; i < this._prehandcards.length; i++) {
    //             preCards.push(this._prehandcards[i]);
    //         }
    //     }
    //     var distance = this.getRoom().getIndexDistance(this.getIndex(), this.getRoom().getDealerIndex());
    //     console.log("distanceee")
    //     console.log(distance);
    //     if (distance == 0) {
    //         preCards.push(101);
    //         preCards.push(201);
    //         preCards.push(301);
    //         preCards.push(401);
    //         preCards.push(102);
    //     } else {
    //         preCards.push(111);
    //         preCards.push(112);
    //         preCards.push(113);
    //         preCards.push(213);
    //         preCards.push(211);
    //     }
    //     // else if (distance == 2) {
    //     //     preCards.push(111);
    //     //     preCards.push(211);
    //     //     preCards.push(311);
    //     //     preCards.push(411);
    //     //     preCards.push(212);
    //     // }
    //     var room = this.getRoom();
    //     logger.debug("room=%d noPreCards %j,cards = %j", room.rid(), preCards, this._prehandcards);
    
    //     return preCards;
    // },
});